package cn.ch.train.${module}.service;

import cn.ch.train.common.response.PageResult;
import cn.ch.train.common.util.SnowUtil;
import cn.ch.train.${module}.domain.${Domain};
import cn.ch.train.${module}.domain.${Domain}Example;
import cn.ch.train.${module}.mapper.${Domain}Mapper;
import cn.ch.train.${module}.request.${Domain}QueryParam;
import cn.ch.train.${module}.request.${Domain}SaveParam;
import cn.ch.train.${module}.response.${Domain}QueryResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class ${Domain}Service {
    private static final Logger logger = LoggerFactory.getLogger(${Domain}Service.class);
    @Resource
    private ${Domain}Mapper ${domain}Mapper;

    public void save(${Domain}SaveParam param) {
        DateTime now = DateTime.now();
        ${Domain} ${domain} = BeanUtil.copyProperties(param, ${Domain}.class);
        if (Objects.isNull(${domain}.getId())) {
            ${domain}.setId(SnowUtil.getSnowFlakeNextId());
            ${domain}.setCreateTime(now);
            ${domain}.setUpdateTime(now);
            ${domain}Mapper.insert(${domain});
        } else {
            ${domain}.setUpdateTime(now);
            ${domain}Mapper.updateByPrimaryKey(${domain});
        }
    }

    public PageResult<${Domain}QueryResult> queryList(${Domain}QueryParam param) {
        ${Domain}Example ${domain}Example = new ${Domain}Example();
        ${domain}Example.setOrderByClause("id desc");
        ${Domain}Example.Criteria criteria = ${domain}Example.createCriteria();
        PageHelper.startPage(param.getPageNo(), param.getPageSize());
        List<${Domain}> ${domain}List = ${domain}Mapper.selectByExample(${domain}Example);

        PageInfo<${Domain}> ${domain}PageInfo = new PageInfo<>(${domain}List);
        logger.info("总行数：{}", ${domain}PageInfo.getTotal());
        logger.info("总页数：{}", ${domain}PageInfo.getPages());
        List<${Domain}QueryResult> ${domain}QueryList = BeanUtil.copyToList(${domain}List, ${Domain}QueryResult.class);
        PageResult<${Domain}QueryResult> pageResult = new PageResult<>();
        pageResult.setTotal(${domain}PageInfo.getTotal());
        pageResult.setList(${domain}QueryList);
        return pageResult;
    }

    public void delete(Long id) {
        ${domain}Mapper.deleteByPrimaryKey(id);
    }
}
